import urllib
import sys
import hashlib
import hmac
import base64


def get_encode_str(params):
    """
    transforms parameters to encoded string
    :param params: dict parameters
    :return: string
    """
    list_params = sorted(params.iteritems(), key=lambda d: d[0])
    encode_str = urllib.urlencode(list_params)
    if sys.stdin.encoding is None:
        res = urllib.quote(encode_str.decode('cp936').encode('utf8'), '')
    else:
        res = urllib.quote(encode_str.decode(sys.stdin.encoding).encode('utf8'), '')
    res = res.replace("+", "%20")
    res = res.replace("*", "%2A")
    res = res.replace("%7E", "~")
    return res


def build_string_to_sign(params, method="GET"):
    return "{0}&%2F&{1}".format(method, get_encode_str(params))


def get_sign_string(source, secret):
    h = hmac.new(secret, source, hashlib.sha1)
    signature = base64.encodestring(h.digest()).strip()
    return signature


def get_sign(params, secret):
    return get_sign_string(build_string_to_sign(params), secret+"&")
